from flask import Flask, request
from flask_cors import CORS
from dataUtil import mongoConnect,sparkConnect
import json
import time

app = Flask(__name__)
CORS(app, resources={r'/*'}, supports_credentials=True)


@app.route("/get_rules", methods=["POST", "GET"])
def get_rules_by_topic():
    data = request.args.get("topic")
    result = mongoConnect.get_rules_by_topic(data)
    print(result)
    results = []
    for i in result["results"]:
        cur_id = i['id']
        cur_name = i['name']
        results.append({
            'value': cur_id,
            'label': cur_name
        })
    return json.dumps(results, ensure_ascii=False)


@app.route("/get_rulescontent", methods=["POST", "GET"])
def get_rulescontent_by_id():
    data = request.args.get("ids")
    ids = data.split(",")
    results = []
    result = mongoConnect.get_rules_by_ids(ids)
    # print(result)
    for cur_rule in result['results']:
        cur_re = {}
        cur_re["id"] = cur_rule["id"]
        cur_re["name"] = cur_rule["name"]
        cur_re['tags'] = []
        tag_res = mongoConnect.get_labels_by_ids(cur_rule['tags'])['results']
        for cur_tag in tag_res:
            print(cur_tag)
            tmp_tag = {
                'id': cur_tag['id'],
                'name': cur_tag['name']
            }
            cur_re['tags'].append(tmp_tag)
        results.append(cur_re)
    return json.dumps(results, ensure_ascii=False)


@app.route("/change_rule", methods=["POST", "GET"])
def change_rule_by_id():
    data = json.loads(request.args.get("data"))
    id = data['id']
    print(data)
    rule = mongoConnect.get_rules_by_ids([id])['results'][0]
    rule['tags'] = []
    for cur_tag in data['tags']:
        rule['tags'].append(cur_tag['id'])
    mongoConnect.del_a_rule(id)
    mongoConnect.insert_a_rule(rule)
    return "success"


@app.route("/delete_rule", methods=["POST", "GET"])
def delete_rule_by_id():
    data = json.loads(request.args.get("data"))
    id = data['id']
    print(data)
    mongoConnect.del_a_rule(id)
    return "success"


@app.route("/add_rule", methods=["POST", "GET"])
def add_rule():
    data = request.data
    data = json.loads(str(data, 'utf-8'))
    cur_time = time.time()
    rule_id = str(hash(str(cur_time) + str(data))%10000)
    print(data)
    name = data['name']
    print(name)
    tags_str = data['tags']
    tag_ids = []
    for tag_str in tags_str:
        tmp = tag_str.split("#")
        id = tmp[0]
        tag_ids.append(id)
    print(tag_ids)
    mongoConnect.insert_a_rule({
        'id': rule_id,
        'name': name,
        'topic': 'antipoor',
        'tags': tag_ids
    })
    return "success"


@app.route("/get_rule_table", methods=["POST", "GET"])
def get_rule_table():
    rule_id = request.args.get("id")
    cols = request.args.get("cols")
    topic = request.args.get("topic")
    page = int(request.args.get("page"))
    print(topic)
    cols = cols.split(',')
    print(cols)
    rule = mongoConnect.get_rules_by_ids([rule_id])
    tag_ids = rule['results'][0]['tags']
    print(tag_ids)
    ids = sparkConnect.get_group_by_tags(tag_ids)
    total = len(ids)
    if page*10 > total:
        end = total
    else:
        end = page * 10
    print((page-1)*10, end)
    results = sparkConnect.get_item_info_by_ids_and_cols(ids[(page-1)*10:end], cols, topic)
    # print(results)
    return json.dumps({"results": results, "total": total})


# the func get a list of item_id
def rule_function(rule_id, func):
    rule = mongoConnect.get_rules_by_ids([rule_id])
    tag_ids = rule['results'][0]['tags']
    results = sparkConnect.get_group_by_tags(tag_ids)
    return func(results)


if __name__ == "__main__":
    import setproctitle
    setproctitle.setproctitle("bdmo-rule")
    app.debug = True
    app.run(host='0.0.0.0', port=5004)
